package main

import (
	"context"
	"fmt"
	"github.com/apache/thrift/lib/go/thrift"
	"github.com/tianyunchong/thrift_route/dbconn"
	"github.com/tianyunchong/thrift_route/route"
	"github.com/tyz/orm/mongo"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"log"
	"time"
)

type DataServiceImpl struct {

}


func (dataService * DataServiceImpl)GetRoute(ctx context.Context, data *route.Data)(r * route.ResData, err error) {
	//查询数据库获取对应的数据
	model := mongo.Model{}
	defer model.Close()
	model.Init("supsite", "usersite_route", session)
	resInfo := model.FindOne(bson.M{
		"siteid": bson.ObjectIdHex(data.Siteid),
		"url":    data.RequestURI,
	})
	res := route.ResData{
		ID: (*resInfo)["_id"].(bson.ObjectId).Hex(),
		Siteid:(*resInfo)["siteid"].(bson.ObjectId).Hex(),
		Param: (*resInfo)["param"].(string),
		Type: 1,
		Mca: (*resInfo)["mca"].(string),
		URL: (*resInfo)["url"].(string),
		Hash: (*resInfo)["hash"].(string),
		Hashid: (*resInfo)["hashid"].(bson.ObjectId).Hex(),
		Addtime: int32((*resInfo)["addtime"].(time.Time).Unix()),
		Uptime: int32((*resInfo)["uptime"].(time.Time).Unix()),
	}
	return &res, nil
}

var listen = "localhost:8080"
var session * mgo.Session
func main()  {
	session =  dbconn.InitMongoLocalSession(bson.M{
		"uri" : "192.168.8.189:27018",
		"timeout" : 5,
		"database" : "supsite",
		"source":"admin",
		"pool" : 100,
	})
	handler := &DataServiceImpl{}
	procesor := route.NewDataServiceProcessor(handler)
	serverTransport, err := thrift.NewTServerSocket(listen)
	if err != nil {
		log.Fatalln("Error:", err)
	}
	//传输器
	transportFactory := thrift.NewTBufferedTransportFactory(10000000)
	//传输协议
	protocolFactory := thrift.NewTBinaryProtocolFactoryDefault()
	//服务器
	server := thrift.NewTSimpleServer4(procesor, serverTransport, transportFactory, protocolFactory)
	fmt.Println("Running at:", listen)
	server.Serve()
}
